package org.msn.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.msn.codec.MsgpackDecoder;
import org.msn.codec.MsgpackEncoder;
import org.msn.server.database.DatabaseStrategy;
import org.msn.server.database.Repository;
import org.msn.server.handler.impl.DefaultServerHandlerImpl;
import org.msn.util.YamlUtil;

import java.io.FileNotFoundException;
import java.util.Map;

@Slf4j
public class ServerBoot {
    private static Map<String, Object> map;
    private static DatabaseStrategy databaseStrategy = new DatabaseStrategy();
    private static Repository repository;

    static {
        try {
            map = YamlUtil.read("server");
            repository = databaseStrategy.createDatabaseLink((String) map.get("type"), (Map<String, Object>) map.get("database"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ServerChannelInitializer());

            log.info("聊天服务器启动 端口 : {}", map.get("port"));

            ChannelFuture channelFuture = bootstrap.bind((Integer) map.get("port")).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    private static class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            socketChannel.pipeline()
//                    .addLast(new IdleStateHandler(0, 4, 0, TimeUnit.SECONDS))
                    .addLast(new MsgpackEncoder())
                    .addLast(new MsgpackDecoder())
                    .addLast(new DefaultServerHandlerImpl(repository))
                    .addLast(new LoggingHandler(LogLevel.INFO));
        }
    }
}
